package com.cangshi.filter;

import com.cangshi.permission.entity.ErrorJSONObject;
import com.cangshi.permission.exception.CheckFailedException;
import com.cangshi.permission.exception.PermissionException;
import com.cangshi.permission.exception.PermissionInitException;
import com.cangshi.permission.filter.PermissionDefaultFilter;
import com.cangshi.permission.holder.CurrentHolder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Eoly on 2017/4/1.
 */
public class UserPermissionFilter extends PermissionDefaultFilter{

    @Override
    protected void doWhileFail(HttpServletRequest request, HttpServletResponse response, FilterChain chain, PermissionException e) throws IOException, ServletException {
        super.doWhileFail(request, response, chain, e);

        ErrorJSONObject errorJSONObject;

        if (null != e) {
            if(e instanceof PermissionInitException){
                errorJSONObject = new ErrorJSONObject(111, "服务端设置错误");
            }else if(e instanceof CheckFailedException){
                errorJSONObject = new ErrorJSONObject(201, e.getMessage());
            }else {
                errorJSONObject = new ErrorJSONObject(-99, e.getMessage());
            }
        }else {
            errorJSONObject = new ErrorJSONObject(111, "用户权限不足");
        }

        CurrentHolder.writeErrorUTF8(response, errorJSONObject);

    }
}
